
// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

cc.Class({
    extends: cc.Component,

    properties: {
        className: {
            default: "PokerScene_psz",
            visible: false
        },
        maxPerson: {
            default: 5,
            visible: false,
        },
        roomData: {
            default: null,
            visible: false
        },
        uid2playerInfo: {
            default: {},
            visible: false
        },
        seat2uid: {
            default: {},
            visible: false
        },
        scorenode: {
            default: [],
            type: cc.Node
        },
        headnode: {
            default: [],
            type: cc.Node
        },
        prepare: {
            default: [],
            type: cc.Node
        },
        nickname: {
            default: [],
            type: cc.Label
        },
        totalscore: {
            default: [],
            type: cc.Label
        },
        score: {
            default: [],
            type: cc.Label
        },
        cardnode: {
            default: [],
            type: cc.Node
        },
        flagnode: {
            default: [],
            type: cc.Node
        },
        btn_chips: {
            default: [],
            type: cc.Button
        },
        pokerbgs: {
            default: {},
            // type: cc.Sprite,
            visible: false
        },
        btn_ready: {
            default: null,
            type: cc.Button
        },
        poker_frames: {
            default: null,
            type: cc.SpriteAtlas
        },
        pokerbg: {
            default: null,
            type: cc.Prefab,
            displayName: "pokerbg"
        },
        dealnode: {
            default: null,
            type: cc.Node,
            displayName: "dealnode"
        },
        options: {
            default: null,
            type: cc.Node
        },
        qipai: {
            default: null,
            type: cc.Sprite,
        },
        btn_kanpai: {
            default: null,
            type: cc.Node,
        },
        bipai: {
            default: null,
            type: cc.Sprite,
        },
        jiazhu: {
            default: null,
            type: cc.Sprite,
        },
        genzhu: {
            default: null,
            type: cc.Sprite,
        },
        jia_bg: {
            default: null,
            type: cc.Sprite,
        },
        pk_Prefab: {
            default: null,
            type: cc.Prefab
        },
        prefab_jiesuan: {
            default: null,
            type: cc.Prefab
        },
    },
    ctor: function () {
        console.log("PokerScene_psz ctor...");
    },
    setData: function (data) {
        console.log("PokerScene_psz setData...");
    },
    onLoad() {
        var self = this;
        self.clearTable();

        network.addListener(this.className, "dealCards", function (data) {
            self.dealCards();
            for (var i = 0; i < self.maxPerson; i++) {
                self.prepare[i].active = false;
            }
        });
        network.addListener(this.className, "joinRoom", function (data) {
            self.roomData = data;
            self.onPlayerEnter();
        });
        network.addListener(self.className, MessageId.PrepareBroadcast, function (data) {
            var prepares = data["prepares"];
            for (var i = 0; i < prepares.length; i++) {
                var obj = prepares[i];
                if (DataManager.ownerUid === obj.uid) {
                    self.btn_ready.node.active = !obj.prepare;
                }
                var player = self.uid2playerInfo[obj.uid];
                if (player) {
                    self.prepare[player.seat].active = obj.prepare;
                }
            }
            self.dealnode.removeAllChildren();

            for (var i = 0; i < self.maxPerson; i++) {
                // this.scorenode[i].active = false;
                // this.headnode[i].active = false;
                self.cardnode[i].active = false;
                self.flagnode[i].active = false;
                self.flagnode[i].getChildByName("yiqipai").active = false;
                self.flagnode[i].getChildByName("yikanpai").active = false;
                self.flagnode[i].getChildByName("bipaishu").active = false;
                var pk = cc.find("pk" + i, self.node);
                if (pk) {
                    pk.active = false;
                }
            }
            self.jia_bg.node.active = false;
            self.options.active = false;
        });
        network.addListener(self.className, "prepare", function (data) {
            if (DataManager.ownerUid === data.uid) {
                self.btn_ready.node.active = !data.prepare;
            }
            var player = self.uid2playerInfo[data.uid];
            if (player) {
                self.prepare[player.seat].active = data.prepare;
                console.log("玩家【" + data.uid + "】准备游戏了！");
            }

        });
        network.addListener(self.className, "exit", function (data) {
            if (data.uid === DataManager.ownerUid) {
                network.removeListener(self.className);
                cc.director.loadScene("HomeScene", function () {
                    console.log("切换场景：HomeScene");
                });
            } else {
                self.removePlayer(data.uid);
                console.log("玩家【" + data.uid + "】退出游戏了！");
            }
        });
        network.addListener(self.className, "operationPk", function (data) {
            if (data.uid === DataManager.ownerUid) {
                for (var i = 0; i < data.bi_arr.length; i++) {
                    (function () {
                        var player = self.uid2playerInfo[data.bi_arr[i]];
                        var pk = cc.find("pk" + player.seat, self.node);
                        if (pk) {
                            pk.active = true;
                        }
                    })();
                }
            }
        });
        network.addListener(self.className, "operation", function (data) {
            if (data.uid === DataManager.ownerUid) {
                // 操作
                self.options.active = true;

                // 弃牌
                self.qipai.node.active = data.can_qi;

                // 是否可以看牌
                self.btn_kanpai.active = data.can_kan;

                // 加注按钮
                var btn_jiazhu = self.jiazhu.getComponent(cc.Button);
                btn_jiazhu.interactable = data.can_jia;
                btn_jiazhu.enableAutoGrayEffect = !data.can_jia;

                // 比牌按钮
                var btn_bipai = self.bipai.getComponent(cc.Button);
                btn_bipai.interactable = data.can_bi;
                btn_bipai.enableAutoGrayEffect = !data.can_bi;

                // 比牌分、跟注分
                self.genzhu.node.getChildByName("label").getComponent(cc.Label).string = "X" + data.gen_score;
                self.bipai.node.getChildByName("label").getComponent(cc.Label).string = "X" + data.bi_score;

                // 加注限制
                for (var i = 0; i < data.zhu_list.length && i < 4; i++) {
                    var btn_chip = self.btn_chips[i];
                    var enable = data.zhu_list[i] > 0;
                    btn_chip.interactable = enable;
                    btn_chip.enableAutoGrayEffect = !enable;
                }
            } else {
                self.options.active = false;
                self.jia_bg.node.active = false;
                console.log("等待他人操作...");
            }
        });
        network.addListener(self.className, "operationBroadcast", function (data) {
            var operation = {
                qi: 0,
                bi: 1,
                jia: 2,
                gen: 3,
                kan: 4,
                pklist: 5, // 可以比牌玩家的uid数组
            };
            var seat = self.uid2playerInfo[data.uid].seat;
            switch (data.operation) {
                case operation.kan:
                    if (DataManager.ownerUid === data.uid) {
                        self.setCards(seat, data.cardArr);
                        self.brightCards(seat);
                    } else {
                        self.flagnode[seat].active = true;
                        self.flagnode[seat].getChildByName("yikanpai").active = true;
                    }
                    console.log(data.uid + "看牌");
                    break;
                case operation.qi:
                    if (DataManager.ownerUid === data.uid) {

                    } else {

                    }
                    self.flagnode[seat].active = true;
                    self.flagnode[seat].getChildByName("yiqipai").active = true;
                    break;
                case operation.bi:
                    network.stop();
                    var pk = cc.instantiate(self.pk_Prefab);
                    pk.getComponent("PK").setData(data);
                    pk.parent = self.node;
                    for (var i = 0; i < 5; i++) {
                        var pk = cc.find("pk" + i, self.node);
                        if (pk) {
                            pk.active = false;
                        }
                    }
                    break;
                case operation.pklist:
                    break;
                default:
                    break;
            }
        })
        network.addListener(self.className, MessageId.Settlement, function (data) {
            self.options.active = false;
            var jiesuan = cc.instantiate(self.prefab_jiesuan);
            jiesuan.parent = self.node;
        });
        network.addListener(self.className, MessageId.TotalSettlement, function (data) {
            log(data);
        });


        network.start();
    },
    onPlayerEnter: function () {
        var players = this.roomData.players;
        for (var i = 0; i < players.length; i++) {
            var player = players[i];
            this.uid2playerInfo[player.uid] = player;
        }

        // 1、调整玩家的seat及玩家信息初始化
        var selfseat = this.uid2playerInfo[DataManager.ownerUid].seat;
        var addnumber = 0;
        if (selfseat !== 0) addnumber = this.maxPerson - selfseat; // 加数
        for (var i = 0; i < players.length && i < this.maxPerson; i++) {
            var player = players[i];
            // 自己的位置不是0时，需要适配下位置
            if (selfseat !== 0) {
                if (player.seat >= selfseat) {
                    player.seat -= selfseat;
                } else {
                    player.seat += addnumber;
                }
            }
            // 玩家信息初始化
            this.headnode[player.seat].active = true;
            this.nickname[player.seat].string = player.nickname;
            this.totalscore[player.seat].string = player.totalscore;
            this.score[player.seat].string = player.score;
            this.prepare[player.seat].active = player.prepare;
            this.seat2uid[player.seat] = player.uid;
        }
        console.log(this.uid2playerInfo);
    },
    removePlayer: function (uid) {
        var player = this.uid2playerInfo[uid];
        this.headnode[player.seat].active = false;
        this.scorenode[player.seat].active = false;
        this.cardnode[player.seat].active = false;
        delete this.uid2playerInfo[uid];
        var players = this.roomData.players;
        for (var i = 0; i < players.length; i++) {
            if (players[i].uid === uid) {
                this.roomData.players.splice(i, 1);
                break;
            }
        }
    },
    clearTable: function () {
        for (var i = 0; i < this.maxPerson; i++) {
            this.scorenode[i].active = false;
            this.headnode[i].active = false;
            this.cardnode[i].active = false;
            this.flagnode[i].active = false;
            this.flagnode[i].getChildByName("yiqipai").active = false;
            this.flagnode[i].getChildByName("yikanpai").active = false;
            this.flagnode[i].getChildByName("bipaishu").active = false;
            var pk = cc.find("pk" + i, this.node);
            if (pk) {
                pk.active = false;
            }
        }
        this.jia_bg.node.active = false;
        this.options.active = false;
    },
    dealCards: function (callfunc) {
        var self = this;
        var time = 0; // 发牌次数
        var isCall = false;
        var zorder = 3 * self.maxPerson * 10;
        var players = self.roomData.players;
        for (var index = 0; index < 3; index++) {
            for (var i = 0; i < players.length; i++) {
                var seat = players[i].seat;
                var pokerbg = cc.instantiate(this.pokerbg);
                pokerbg.x = 0;
                pokerbg.y = 125;
                pokerbg.setLocalZOrder(zorder--);
                pokerbg.parent = this.dealnode;
                pokerbg.name = "pokerbg-" + seat + "-" + index;
                var cardsnode = this.cardnode[seat];
                var card = cardsnode.getChildByName("card" + index);
                card.tag = index;
                var x = card.x + cardsnode.x;
                var y = card.y + cardsnode.y;

                // console.log("index = " + index + " | i = " + i);
                time++;
                var actionEnd = function (card, isCall, index, callfunc) {
                    card.setLocalZOrder(card.tag);
                    // console.log("zoreder ==== " + card.tag);
                    // sprite.removeFromParent(true);

                    // pai.setVisible(true);
                    // pai.getParent().setVisible(true);

                    // console.log("isCall: " + isCall + " | index: " + index);
                    if (!isCall && index === 2 && callfunc) {
                        isCall = true;
                        callfunc();
                    }
                }
                pokerbg.runAction(cc.sequence(
                    cc.delayTime(time * 0.15),
                    // cc.callFunc(function () {
                    //     playEffect('vfapai_bg');
                    // }),
                    cc.spawn(
                        cc.moveTo(0.2, x, y),
                        cc.scaleTo(0.2, card.scaleX),
                        cc.rotateBy(0.2, 360)
                    ),
                    cc.callFunc(actionEnd)
                ))
            }
        }
        console.log(this.dealnode.getChildren().length);
    },
    setCards: function (seat, cardArr) {
        // 0 - 53为扑克牌id
        // 0:黑桃、1:红桃、2:梅花、3:方块
        var PokerCard = function (id) {
            var color = Math.floor(id / 13);
            var colorFrame = "poker-color_" + color;
            var big_color = colorFrame;
            var small_color = colorFrame;
            var number = id % 13;
            var numberFrame = { 0: "poker-black_", 1: "poker-red_" }[color % 2] + number;
            var des = { 0: "黑桃", 1: "红桃", 2: "梅花", 3: "方块", 4: "王" }[color];
            var sort = number;
            if (color < 4) {
                if (number < 1) {
                    des += "A";
                } else if (number < 10) {
                    des += (number + 1);
                } else {
                    des += { 10: "J", 11: "Q", 12: "K" }[number];
                    big_color = "poker-color_" + number + "_" + color;
                }
            } else {
                des = { 0: "小王", 1: "大王" }[number];
                numberFrame = "poker-num_king" + number;
                colorFrame = "poker-color_king" + number;
            }
            if (number < 2) {
                sort += 13;
            }
            return {
                id: id,        // id
                color: color,  // 类型
                number: number,// 数字
                des: des,      // 描述
                numberFrame: numberFrame, // 数字精灵帧
                colorFrame: colorFrame,   // 类型精灵帧
                big_color: big_color,
                small_color: small_color,
                sort: sort,// 排序值
            };
        }
        cardArr.sort(function (a, b) {
            return a - b;
        });
        for (let i = 0; i < cardArr.length; i++) {
            let pokerCard = PokerCard(cardArr[i]);
            let card = this.cardnode[seat].getChildByName("card" + i);
            let number = card.getChildByName("number");
            let bigcolor = card.getChildByName("bigcolor");
            let smallcolor = card.getChildByName("samllcolor");
            bigcolor.getComponent(cc.Sprite).spriteFrame = this.poker_frames.getSpriteFrame(pokerCard.big_color);
            smallcolor.getComponent(cc.Sprite).spriteFrame = this.poker_frames.getSpriteFrame(pokerCard.small_color);
            number.getComponent(cc.Sprite).spriteFrame = this.poker_frames.getSpriteFrame(pokerCard.numberFrame);
            // card.getComponent(cc.Sprite).spriteFrame = this.poker_frames.getSpriteFrame("poker-poker_face");
            // bigcolor.getComponent(cc.Sprite).spriteFrame = this.poker_frames.getSpriteFrame("poker-color_0");
            console.log(pokerCard);
        }
    },
    /**
     * 亮牌
     * seat: 需要亮牌的座位号
     * callfuc: 亮牌结束后的回调
     */
    brightCards: function (index, callfunc) {
        var self = this;
        var flipTime = 0.175;
        for (var i = 0; i < 3; i++) {
            (function () {
                // 1、牌背
                var pokerbg = self.dealnode.getChildByName("pokerbg-" + index + "-" + i);
                var scaleX = pokerbg.scaleX;
                pokerbg.scaleX *= -1;
                pokerbg.runAction(cc.sequence(
                    cc.spawn(
                        cc.scaleTo(flipTime, 0, scaleX),
                        cc.skewTo(flipTime, 0, 30)
                    ),
                    cc.callFunc(function () {
                        pokerbg.active = false;
                        pokerbg.active = null;
                    }),
                ));

                // 2、牌面
                var poker_faces = self.cardnode[index];
                poker_faces.active = true;
                var poker_face = poker_faces.getChildByName("card" + i);
                var scaleX = poker_face.scaleX;
                poker_face.scaleX *= -1;
                poker_face.runAction(cc.sequence(
                    cc.spawn(
                        cc.scaleTo(flipTime, 0, scaleX),
                        cc.skewTo(flipTime, 0, 30)
                    ),
                    cc.callFunc(function (poker_faces) {
                        poker_faces.active = true;
                    }),
                    cc.spawn(
                        cc.scaleTo(flipTime, scaleX, scaleX),
                        cc.skewTo(flipTime, 0, 0)
                    ),
                    cc.callFunc(function (poker_face) {
                        if (poker_face.tag === 2 && callfunc) {
                            callfunc();
                        }
                    })
                ));
            })();
        }
    },
    onPK: function (event, customData) {
        var bi_uid = this.uid2playerInfo[this.seat2uid[customData]].uid;
        network.send("operation", { operation: 1, bi_uid: bi_uid });
    },
    onOperation: function (target, customData) {
        var operation = { qi: 0, bi: 1, jia: 2, gen: 3, kan: 4 };
        var messageObj = {};
        if (customData === "kanpai") {
            network.send("operation", { operation: operation.kan });
        } else if (customData === "qipai") {
            messageObj.code = operation.qi;
            network.send("operation", { operation: operation.qi });
        } else if (customData === "bipai") {
            network.send("operation", { operation: operation.bi, bi_uid: 0 });
        } else if (customData === "jiazhu") {
            this.jia_bg.node.active = !this.jia_bg.node.active;
        } else if (customData === "genzhu") {
            network.send("operation", { operation: operation.gen });
        } else if (customData === "2" || customData === "3" || customData === "4" || customData === "5") {
            network.send("operation", { operation: operation.jia, beishu: parseInt(customData) });
        } else {
            console.log("未定义的操作...");
        }
    },
    onPrepare: function () {
        this.dealnode.removeAllChildren();
        network.send("prepare", { prepare: true });
    },
    onVoice: function () {
    },
    onExit: function () {
        network.send("exit");
    }
});